import { Color, Graphics, Node, UITransform } from "cc";
import { QRCode, QRErrorCorrectLevel } from "./QRCode";

export default class QRCodeHelper {

    public static drawQRCode(codeNode: Node, url: string = "http://www.baidu.com") {
        let qrCode: QRCode = new QRCode(-1, QRErrorCorrectLevel.H);
        qrCode.addData(url);
        qrCode.make();
        let ctx: Graphics = codeNode.addComponent(Graphics);
        // ctx.lineWidth = 2;
        let tileW: number = codeNode.getComponent(UITransform).width / qrCode.getModuleCount();
        let tileH: number = codeNode.getComponent(UITransform).height / qrCode.getModuleCount();
        for (let row = 0; row < qrCode.getModuleCount(); row++) {
            for (let col = 0; col < qrCode.getModuleCount(); col++) {
                if (qrCode.isDark(row, col)) {
                    ctx.fillColor = Color.BLACK;
                } else {
                    ctx.fillColor = Color.WHITE;
                }
                let w = (col + 1) * tileW - (col * tileW);
                let h = (row + 1) * tileW - (row * tileW);
                ctx.rect(col * tileW - codeNode.getComponent(UITransform).width / 2, row * tileH - codeNode.getComponent(UITransform).height / 2, w, h);
                ctx.fill();
            }
        }
    }

}
